document.body.addEventListener('click', event => {
    if (event.target.closest('[data-favorites]')) {
        addRemoveFavorites(event);
    }

    if (event.target.closest('[data-quotes-window]')) {
        showQuotesWindow(event);

    } else if (event.target.closest('[data-close-quotes-window]') ) {
        base.closeWindowForDisplayingQuotes(event);
    }
})

if (document.querySelector('.book-big')) {

    const url = document.location.href + '?information=true/'
    base.sendAjaxRequest(url, 'GET')
        .then(result => {
            showAmountOfReading(result);
            displayFavorites(result);

        })

}


function showQuotesWindow(event) {
    // Показывам цитаты

    const html = base.showWindowForDisplayingQuotes(event);
}

function addRemoveFavorites(event) {
    event.preventDefault();

    const token = document.querySelector('[data-favorites]>form>input[name="csrfmiddlewaretoken"]').value
    const isFavorites = event.target.closest('[data-favorites]').dataset.favorites.toLowerCase();
    const initial_url = document.location.href;

    if (isFavorites == 'true') {
        console.log(1)
        removeFavorites(event, initial_url, token);
    } else if (isFavorites == 'false') {
        console.log(0)
        addFavorites(event, initial_url, token);
    }


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function removeFavorites(event, initial_url, token) {
        const url = initial_url + 'remove_favorites/';
        base.sendAjaxRequest(url, 'POST', {'token': token})
            .then(() => {
                document.querySelector('[data-favorites] i').style.cssText = `
                    color: #4c4c4c;
                    transition: color .3s ease-in;
                `
                event.target.closest('[data-favorites]').dataset.favorites = 'false'
            })
    }

    function addFavorites(event, initial_url, token) {
        const url = initial_url + 'add_favorites/';
        base.sendAjaxRequest(url, 'POST', {'token': token})
            .then(() => {
                document.querySelector('[data-favorites] i').style.cssText = `
                    color: #f5dc65;
                    transition: color .3s ease-in;
                `
                event.target.closest('[data-favorites]').dataset.favorites = 'true'
            })
    }
}

function displayFavorites(result) {
    if (result.favorites) {
        document.querySelector('.fa-star').style.fontWeight = 'bold';
        document.querySelector('.fa-star').style.color = '#f5dc65';
    }
}


function showAmountOfReading(result) {
    // Показываем количество прочитанного

    const readPercentages = Math.trunc(result.last_page / result.volume * 100);
    const value = readPercentages + '%';
    document.querySelector('.number-of-pages>.percentages').innerHTML = value;
    document.querySelector('.now').style.width = value;
}